import axios from 'axios'
import store from '@/store/index'
import router from '@/router/index'

export const baseURL = 'https://apipc-xiaotuxian-front.itheima.net/'

const requests = axios.create({
    baseURL,
    timeout: 5000 // 5秒
})

requests.interceptors.request.use(config => {
    // 获取token
    const { profile } = store.state.user
    if (profile.token) {
        config.headers.Authorization = `Bearer ${ profile.token}`
    }
    return config
}, err => {
    return Promise.reject(err)
})

requests.interceptors.response.use(res => {
    // 取出data数据
    return res.data
}, err => {
    // 401 状态码
    if (err.response && err.response.status === 401) {
        // 1 清空无效信息
        // 2 跳转至登录页面
        // 3 携带当前路由信息
        store.commit('user/SET_USER', {})
        // router 是一个ref  故需要 .value获取属性
        const fullPath = encodeURIComponent(router.currentRoute.value.fullPath)
        router.push(`/login?redirectUrl=${fullPath}`)
    }
    return Promise.reject(err)
})

// 暴露方法
export default (url, method, submotData) => {
    return requests({
        url,
        method,
        [method.toLowerCase() === 'get' ? 'params' : 'data']: submotData
    }
  )                
}